<template xmlns:el-col="http://www.w3.org/1999/html">
  <div class="all_container">
    <div class="order_detail--container">
      <div class="order_detail--header">
        <div class="order_detail_left">
          <title-view
            :title="
              nameTitle === '变更' ? '增减项单号：' + detailDate.reformNo || '' : nameTitle + '单号：' + detailDate.reformNo || ''
            "
          />
          <div class="reform-state" :class="getStatusClass(reformState)">
            {{ getStatusLabel(reformState) }}
          </div>
        </div>
        <el-button type="info" color="#F2F3F5" @click="handleGoto" v-if="route.query.show">返回上一页</el-button>
      </div>
      <div
        class="order_detail--title"
        v-if="
          (reformState == 10 && titleleft !== '' && titleleft !== null) ||
          (reformState == 5 && titleleft !== '' && titleleft !== null)
        "
      >
        <div class="detail_title_item">拒绝理由：</div>
        <div class="detail_title_right">
          <show-more-text :text="titleleft"></show-more-text>
        </div>
      </div>
      <div class="order_detail--body">
        <div class="order_detail--titlenew">
          <div class="order_detail--amount">
            <span>{{ detailDate.customerTotalCollectionAmount ? "需退款金额合计" : "需收款金额合计" }}</span>
            <span style="color: #ff3333"
              >¥{{ detailDate.customerTotalCollectionAmount || detailDate.customerTotalPaymentDue || "0" }}</span
            >
          </div>
          <div class="order_detail--dividernew"></div>
          <div class="order_detail--amount">
            <span>给客户赔偿金额</span>
            <span>¥{{ detailDate.customerCompensationAmount || "0" }}</span>
          </div>
          <div class="order_detail--dividernew"></div>
          <div class="order_detail--amount">
            <span>报价{{ nameTitle === "变更" ? "增减项" : nameTitle }}单金额</span>
            <span>¥{{ detailDate.quoteChangeAmount || "0" }}</span>
          </div>
          <div class="order_detail--dividernew"></div>
          <div class="order_detail--amount">
            <span>{{ detailDate.uncollectedAmount ? "未收款金额" : "未退款金额" }}</span>
            <span>¥{{ detailDate.uncollectedAmount ? detailDate.uncollectedAmount : detailDate.unrefundedAmount }}</span>
            <span
              :style="{ fontSize: '12px', color: detailDate.slipRecordState === 1 ? '#ff9900' : '#ff3333' }"
              v-if="detailDate.slipRecordState && detailDate.slipRecordState !== 2"
              >{{ detailDate.slipRecordState === 1 ? "待审批" : "审批不通过" }}</span
            >
          </div>
        </div>

        <div class="order_body--title">
          <div class="order_body--titleleft">基础信息</div>
          <div class="order_body--titleright">(内部可见)</div>
        </div>
        <el-row style="margin: 10px 0 0" :gutter="24" class="order_detail--row">
          <el-col :span="4" class="order_detail--bgcorlor"> {{ nameTitle === "变更" ? "增减项" : nameTitle }}分类 </el-col>
          <el-col :span="4">{{ detailDate.reformTypeName || "" }}</el-col>

          <el-col :span="4" class="order_detail--bgcorlor">关联的报价变更单</el-col>
          <el-col :span="4" class="order_detail--line" @click="handleGotoline(detailDate.exchangeBudgetId)">
            {{ detailDate.exchangeBudgetId || "" }}
          </el-col>
          <el-col :span="4" class="order_detail--bgcorlor">{{ nameTitle }}模板</el-col>
          <el-col :span="4" class="order_detail--borderright">
            {{ detailDate.packageName || "" }}
          </el-col>

          <el-col :span="4" class="order_detail--bgcorlor">是否首次收款后开展任务和核量</el-col>
          <el-col :span="4">{{ detailDate.isFirstPaymentReceived == 1 ? "是" : "否" }}</el-col>

          <el-col :span="4" class="order_detail--bgcorlor">是否业主可见</el-col>
          <el-col :span="4">{{ detailDate.isVisible == 1 ? "是" : "否" }}</el-col>

          <el-col :span="4" class="order_detail--bgcorlor">是否需业主确认</el-col>
          <el-col :span="4" class="order_detail--borderright"
            >{{ detailDate.isOwnerConfirmationRequired == 1 ? "是" : "否" }}
          </el-col>

          <el-col :span="4" class="order_detail--bgcorlor order_detail--borderbottom"> 问题描述</el-col>
          <el-col :span="20" class="order_detail--borderright order_detail--borderbottom">
            {{ detailDate.reformDesc || "" }}
          </el-col>

          <el-col :span="4" class="order_detail--borderbottom order_detail--bgcorlor" v-if="detailDate.solution">
            解决方案
          </el-col>
          <el-col :span="20" class="order_detail--borderbottom order_detail--borderright" v-if="detailDate.solution">
            {{ detailDate.solution || "" }}
          </el-col>
        </el-row>
        <div style="height: 10px; width: 100%"></div>

        <el-collapse-transition>
          <div v-show="picUrls.length !== 0 || videoUrls.length !== 0" class="order_show--container">
            <div class="picUrls_flex_top" v-if="picUrls.length !== 0">
              <div style="width: 58px; color: #86909c">图片</div>
              <div class="picUrls_flex_countent">
                <div v-if="picUrls.length > 0">
                  <el-image
                    v-for="item in picUrls"
                    :key="item"
                    :preview-src-list="[item]"
                    class="order_show--img"
                    :src="item"
                    fit="fill"
                  />
                </div>
              </div>
            </div>

            <div class="picUrls_flex_top" v-if="videoUrls.length !== 0">
              <div style="width: 58px; color: #86909c">视频</div>
              <div v-if="videoUrls.length > 0" class="picUrls_flex_countent">
                <div v-for="item in videoUrls" :key="item">
                  <video class="order_show--video" v-if="item" :src="item" controls style="object-fit: cover"></video>
                </div>
              </div>
            </div>
          </div>
        </el-collapse-transition>

        <div v-if="detailDate.isVisible == 1">
          <div class="order_body--title" style="margin-top: 24px">
            <div class="order_body--titleleft">基础信息</div>
            <div class="order_body--titleright">(业主可见)</div>
          </div>

          <el-row style="margin: 10px 0 0" :gutter="24" class="order_detail--row">
            <el-col :span="4" class="order_detail--borderbottom order_detail--bgcorlor">{{ nameTitle }}内容</el-col>
            <el-col
              :span="detailDate.expectedCompletionTime ? 4 : 8"
              class="order_detail--borderbottom order_detail--borderright"
            >
              {{ detailDate.ownerVisibleContent || "" }}
            </el-col>
            <el-col :span="4" class="order_detail--borderbottom order_detail--bgcorlor" v-if="detailDate.expectedCompletionTime"
              >预计完成日期
            </el-col>
            <el-col :span="4" class="order_detail--borderbottom" v-if="detailDate.expectedCompletionTime">
              {{ detailDate.expectedCompletionTime }}
            </el-col>
            <el-col :span="4" class="order_detail--borderbottom order_detail--bgcorlor">延期天数</el-col>
            <el-col
              :span="detailDate.expectedCompletionTime ? 4 : 8"
              class="order_detail--borderbottom order_detail--borderright"
            >
              {{ detailDate.expectedDelayDays }}
            </el-col>
          </el-row>

          <div style="height: 10px"></div>

          <el-collapse-transition>
            <div v-show="ownerVisibleVideoUrls.length !== 0 || ownerVisiblePicUrls.length !== 0" class="order_show--container">
              <div class="picUrls_flex_top" v-if="ownerVisiblePicUrls.length !== 0">
                <div style="width: 58px; color: #86909c">图片</div>
                <div class="picUrls_flex_countent">
                  <div v-if="ownerVisiblePicUrls.length > 0">
                    <el-image
                      v-for="item in ownerVisiblePicUrls"
                      :key="item"
                      :preview-src-list="[item]"
                      class="order_show--img"
                      :src="item"
                      fit="fill"
                    />
                  </div>
                </div>
              </div>
              <div class="picUrls_flex_top" v-if="ownerVisibleVideoUrls.length !== 0">
                <div style="width: 58px; color: #86909c">视频</div>
                <div v-if="ownerVisibleVideoUrls.length > 0" class="picUrls_flex_countent">
                  <div v-for="item in ownerVisibleVideoUrls" :key="item">
                    <video class="order_show--video" v-if="item" :src="item" controls style="object-fit: cover"></video>
                  </div>
                </div>
              </div>
            </div>
          </el-collapse-transition>
        </div>

        <div
          class="add-order-container-white"
          v-if="returnOrder.itemList.length !== 0 || replacementOrder.itemList.length !== 0"
        ></div>

        <div v-if="returnOrder.itemList.length !== 0">
          <div class="order_table--title">
            <div class="left">
              <title-view title="退货单" :showTagCircle="false" />
            </div>
            <div class="sum">
              <div>
                （费用合计：<span style="color: #ff3333">¥{{ returnOrder.refundBudgetTotlalMoney || 0 }}</span>
              </div>
              <div>
                管理费：<span>¥{{ returnOrder.refundManagerFee || 0 }}</span>
              </div>
              <div>
                税费：<span>¥{{ returnOrder.refundTaxesFee || 0 }}</span>
              </div>
              <div>
                综合项金额：<span>¥{{ returnOrder.refundCustomComprehensiveFee || 0 }}</span>
              </div>
              <div>
                其他费用：<span>¥{{ returnOrder.refundOtherFee || 0 }}</span
                >)
              </div>
            </div>
          </div>
          <el-table
            :data="returnOrder.itemList"
            style="width: 100%"
            border
            :header-cell-style="{ background: '#F2F6FC', color: '#4E5969', 'font-weight': 400, 'font-size': '14px' }"
          >
            <el-table-column prop="serialNo" label="序号" />
            <el-table-column prop="mainPicUrl" label="图片">
              <template #default="{ row }">
                <el-image class="order_show--img" :src="row.mainPicUrl" :fit="fit" />
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="brandName" label="品牌" />
            <el-table-column prop="modeCode" label="型号" />
            <el-table-column prop="productUnit" label="单位" />
            <el-table-column prop="num" label="退换数量" />
            <el-table-column prop="exchangeAmount" :width="160" :label="nameTitle + '金额（退款金额)'" />
          </el-table>
        </div>

        <div v-if="replacementOrder.itemList.length !== 0">
          <div class="order_table--title">
            <div class="left">
              <title-view title="换补单" :showTagCircle="false" />
            </div>
            <div class="sum">
              <div>
                （费用合计：<span style="color: #ff3333">¥{{ replacementOrder.budgetTotlalMoney || 0 }}</span>
              </div>
              <div>
                管理费：<span>¥{{ replacementOrder.managerFee || 0 }}</span>
              </div>
              <div>
                税费：<span>¥{{ replacementOrder.taxesFee || 0 }}</span>
              </div>
              <div>
                综合项金额：<span>¥{{ replacementOrder.customComprehensiveFee || 0 }}</span>
              </div>
              <div>
                其他费用：<span>¥{{ replacementOrder.otherFee || 0 }}</span>
                )
              </div>
            </div>
          </div>
          <el-table
            :data="replacementOrder.itemList"
            style="width: 100%"
            border
            :header-cell-style="{ background: '#F2F6FC', color: '#4E5969', 'font-weight': 400, 'font-size': '14px' }"
          >
            <el-table-column prop="serialNo" label="序号" />
            <el-table-column prop="mainPicUrl" label="图片">
              <template #default="{ row }">
                <el-image class="order_show--img" :src="row.mainPicUrl" :fit="fit" />
              </template>
            </el-table-column>
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="brandName" label="品牌" />
            <el-table-column prop="modeCode" label="型号" />
            <el-table-column prop="productUnit" label="单位" />
            <el-table-column prop="num" label="退换数量" />
            <el-table-column prop="exchangeAmount" :width="160" :label="nameTitle + '金额'" />
          </el-table>
        </div>
      </div>
    </div>

    <div class="operate_right">
      <div class="operate_right-content mb20 top">
        <div class="order_detail--header">
          <div class="order_detail_left">
            <title-view :title="detailDate.customerTotalCollectionAmount ? '退款信息' : '收款信息'" />
          </div>
        </div>
        <div class="money-header">
          <div class="flex" style="justify-content: space-between">
            <div>
              已{{ detailDate.customerTotalCollectionAmount ? "退" : "收" }}款：¥{{
                detailDate.customerTotalCollectionAmount
                  ? detailDate.amountRefunded || "0.00"
                  : detailDate.amountReceived || "0.00"
              }}
            </div>
            <div>
              未{{ detailDate.customerTotalCollectionAmount ? "退" : "收" }}款：¥{{
                detailDate.customerTotalCollectionAmount
                  ? detailDate.unrefundedAmoun || "0.00"
                  : detailDate.uncollectedAmount || "0.00"
              }}
            </div>
          </div>
        </div>
        <div class="money-list-content" v-if="detailDate.slipRecordsList?.length > 0">
          <div class="money-list" v-for="item in detailDate.slipRecordsList" :key="item">
            <div class="flex">
              <div class="money-text" :class="{ refund: detailDate.customerTotalCollectionAmount }">
                {{ detailDate.customerTotalCollectionAmount ? "退" : "收" }}
              </div>
              <div class="money-right">
                <div class="num">¥{{ item.inMoney }}</div>
                <div class="flex time">
                  <div>{{ payTypeList[item.payType - 1] || "--" }}</div>
                  <div class="flex">
                    <el-icon style="margin-right: 5px">
                      <Clock />
                    </el-icon>
                    <div>{{ item.receiptDate }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
        <el-empty v-else description="暂无数据" image-size="80" style="padding: 0" />
      </div>
      <div class="operate_right-content bottom">
        <div class="order_detail--header">
          <div class="order_detail_left">
            <title-view title="操作记录" />
          </div>
        </div>
        <div class="operate_right_dowm">
          <el-timeline style="max-width: 600px">
            <el-timeline-item
              :icon="MoreFilled"
              type="primary"
              size="large"
              v-for="(item, index) in operationRecords"
              :key="item.operationRecordsId"
            >
              <div class="operate_right_alltext">
                <div class="right_text_time">{{ item.createTime }}</div>
                  <div style="display: flex; font-size: 12px; color: #c0c4cc">
                  <div>{{ item.operationName || "--" }}</div>
                  <div style="width: 12px; color: #c0c4cc; font-weight: 500">丨</div>
                  <el-tooltip
                    :content="item.operationRoleNames == null ? '--' : item.operationRoleNames"
                    placement="bottom"
                    effect="light"
                  >
                    <div style="width: 62px; overflow: hidden; white-space: nowrap; text-overflow: ellipsis">
                      {{ item.operationRoleNames || "--" }}
                    </div>
                  </el-tooltip>
                </div>
              </div>
              <div class="operate_right_lefttext">{{ showoperation(item.operation) }}</div>
              <div
                class="operate_right_card"
                v-show="
                  (item.operationContent && item.operation !== 10 && item.operation !== 5) ||
                  (item.picUrls && item.operation !== 10 && item.operation !== 5) ||
                  (item.videoUrls && item.operation !== 10 && item.operation !== 5)
                "
              >
                <div class="operate_right_cardcontent" ref="contentDom">
                  {{ item.operationContent }}
                </div>
                <div style="height: 12px; width: 100%"></div>

                <div class="operate_right_cardbutton" v-if="!item.showclick">
                  <div
                    @click="handleClick(v.url, 'img')"
                    class="operate_right_footbtnchild"
                    v-for="v in item?.imgdata"
                    :key="v.url"
                  >
                    <img src="@/assets/images/picture.png" style="margin-left: 10px" />
                    <el-tooltip :content="urlname(v.url)" placement="bottom" effect="light">
                      <div style="width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap">
                        {{ urlname(v.url) }}
                      </div>
                    </el-tooltip>
                  </div>

                  <div
                    class="operate_right_footbtnchild"
                    @click="handleClick(v.url, 'video')"
                    v-for="v in item?.videodata"
                    :key="v.url"
                  >
                    <img src="@/assets/images/video.png" style="margin-left: 10px" />
                    <el-tooltip :content="urlname(v.url)" placement="bottom" effect="light">
                      <div style="width: 100px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap">
                        {{ urlname(v.url) }}
                      </div>
                    </el-tooltip>
                  </div>
                </div>

                <div @click="shouzhankaishouqi(item, false, index)" v-if="item.showclick == true" class="operate_right_state">
                  <div class="operate_right_statetext">展开</div>
                  <img src="@/assets/images/kai.png" />
                </div>
                <div @click="shouzhankaishouqi(item, true, index)" v-if="item.showclick == false" class="operate_right_state">
                  <div class="operate_right_statetext">收起</div>
                  <img src="@/assets/images/shou.png" />
                </div>
              </div>
            </el-timeline-item>
          </el-timeline>
        </div>
      </div>
    </div>
    <el-dialog v-model="dialogVisible" :before-close="handleClose" align-center width="30%">
      <ImageVideoPreview :showtype="showtype" :url="url"></ImageVideoPreview>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, nextTick } from "vue";
import { reformDetail } from "@/apis/afterSalesOrder";
import { useRoute, useRouter } from "vue-router";
import showMoreText from "./showMoreText";
import { Clock, MoreFilled } from "@element-plus/icons-vue";
import ImageVideoPreview from "@/components/ImageVideoPreview";

const dialogVisible = ref(false);
const url = ref("");
// const list = ref(["已收款", "已退款"]);
const payTypeList = ref(["账户支付", "现金支付", "预收款支付 ", "借款还款单支付", "预付支付", "退款转预付"]);
const activeIndex = ref(0);
const showtype = ref("");
const route = useRoute();
const router = useRouter();
const detailDate = ref({});
const contentDom = ref();
const returnOrder = ref({
  itemList: []
}); // 退货单
const replacementOrder = ref({
  itemList: []
}); // 换补单
//返回上一页
const picUrls = ref([]);
const videoUrls = ref([]);
const ownerVisiblePicUrls = ref([]);
const ownerVisibleVideoUrls = ref([]);
const nameTitle = ref("整改");
const statusMap = new Map([
  [1, ["warning", "待审核"]],
  [2, ["warning", "待开始"]],
  [3, ["primary", "进行中"]],
  [4, ["success", "已完成"]],
  [5, ["danger", "未通过"]],
  [6, ["info", "已作废"]],
  [7, ["primary", "审批中"]],
  [8, ["warning", "待发起客户确认"]],
  [9, ["primary", "客户确认中"]],
  [10, ["danger", "客户拒绝"]],
  [11, ["warning", "待收款"]]
]);
// 获取状态 CSS 类名
const getStatusClass = state => {
  const [statusClass] = statusMap.get(state) || ["danger", "未知"];
  return `reform-state-${statusClass}`;
};
// 获取状态标签
const getStatusLabel = state => {
  const [, statusLabel] = statusMap.get(state) || ["danger", "未知"];
  return statusLabel;
};

const operationArry = [
  { value: 1, label: "创建" },
  { value: 2, label: "编辑" },
  { value: 3, label: "撤销审批" },
  { value: 4, label: "审核通过" },
  { value: 5, label: "审核未通过" },
  { value: 6, label: "作废" },
  { value: 7, label: "撤销客户确认" },
  { value: 8, label: "发起客户确认" },
  { value: 9, label: "客户确认" },
  { value: 10, label: "客户拒绝" },
  { value: 11, label: "收款" },
  { value: 12, label: "退款" },
  { value: 13, label: "开始任务" }
];
const reformState = ref();
const titleleft = ref();
const operationRecords = ref([]);
const handleClick = (v, type) => {
  url.value = v;
  showtype.value = type;
  dialogVisible.value = true;
};
const urlname = url => {
  // 获取文件名和扩展名
  const fileNameWithExt = url.substring(url.lastIndexOf("/") + 1);
  // 提取文件扩展名
  const extension = fileNameWithExt.substring(fileNameWithExt.lastIndexOf("."));
  // 去掉扩展名部分，提取裸文件名
  const fileName = fileNameWithExt.substring(0, fileNameWithExt.lastIndexOf("."));
  // 解码URL编码的文件名
  const decodedFileName = decodeURIComponent(fileName);
  // 找到最后一个 '-' 的位置，通常附加标识符从这里开始
  const lastDashIndex = decodedFileName.lastIndexOf("-");
  // 去除附加标识符，重建文件名并添加扩展名
  const baseFileName = decodedFileName.substring(0, lastDashIndex).trim() + extension;
  return baseFileName;
};
const getDomHeight = async () => {
  await nextTick();
  operationRecords.value.forEach((item, index) => {
    const num = item.picUrls?.split(",").length + item.videoUrls?.split(",").length;
    if (contentDom.value[index].offsetHeight > 45) {
      item.showclick = true;
    } else if (num > 2) {
      item.showclick = true;
    } else {
      delete item.showclick;
    }
  });
};
const handleActive = i => {
  activeIndex.value = i;
};
const shouzhankaishouqi = (item, show, index) => {
  item.showclick = show;
  if (show == true) {
    contentDom.value[index].classList.remove("operate_right_cardcontentshow");
    contentDom.value[index].classList.add("operate_right_cardcontent");
  } else {
    contentDom.value[index].classList.remove("operate_right_cardcontent");
    contentDom.value[index].classList.add("operate_right_cardcontentshow");
  }
};
const getDetail = async () => {
  const { data } = await reformDetail(route.query.reformId);
  nameTitle.value = data.afterSalesType === 1 ? "整改" : "变更";
  detailDate.value = data;
  titleleft.value = data.refusalReason;
  returnOrder.value = data.exchangeOrderDetail?.returnOrder || { itemList: [] };
  if (returnOrder.value.itemList === null) {
    returnOrder.value.itemList = [];
  }
  replacementOrder.value = data.exchangeOrderDetail?.replacementOrder || { itemList: [] };
  if (replacementOrder.value.itemList === null) {
    replacementOrder.value.itemList = [];
  }

  picUrls.value = data.picUrls ? data.picUrls.split(",") : [];
  videoUrls.value = data.videoUrls ? data.videoUrls.split(",") : [];
  ownerVisiblePicUrls.value = data.ownerVisiblePicUrls ? data.ownerVisiblePicUrls.split(",") : [];
  ownerVisibleVideoUrls.value = data.ownerVisibleVideoUrls ? data.ownerVisibleVideoUrls.split(",") : [];
  reformState.value = data.reformState;
  operationRecords.value = data.operationRecords;
  operationRecords.value.forEach(item => {
    item.showclick = true;
    if (item.picUrls !== null && item.picUrls !== "") {
      item.imgdata = item.picUrls.split(",").map(url => {
        const fragments = url.trim().split(".");
        const type = fragments[fragments.length - 1];
        return { url: url.trim(), type };
      });
    }
    if (item.videoUrls !== null && item.videoUrls !== "") {
      item.videodata = item.videoUrls.split(",").map(url => {
        const fragments = url.trim().split(".");
        const type = fragments[fragments.length - 1];
        return { url: url.trim(), type };
      });
    }
  });
  await getDomHeight();
};
const showoperation = v => {
  return operationArry.find(item => item.value == v).label;
};
const handleGoto = () => {
  if (route.query.afterSalesType) {
    router.push({
      path: "/client-info",
      query: {
        customerId: detailDate.value.customerId,
        afterSalesType: route.query.afterSalesType,
        funcTab: "rectification"
      }
    });
  } else {
    router.go(-1);
  }
};
const handleGotoline = e => {
  if (e) {
    const baseRouter = window.microApp.router.getBaseAppRouter();
    const routeUrl = baseRouter.resolve({
      path: "/designer/quote-price/following/exchangeHistory",
      query: {
        exchangeBudgetId: e
      }
    });
    window.open(routeUrl.href, "_blank");
  }
};
getDetail();
</script>

<style scoped lang="scss">
@use "index";
</style>
